package com.hangar.eforms.config;

import com.hangar.eforms.common.Result;
import com.hangar.eforms.common.exception.BusinessException;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author hwn
 */
@RestControllerAdvice
@Slf4j
public class BaseControllerAdvice {


    @ExceptionHandler(Exception.class)
    public Result<String> globalExceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);
        return Result.error("系统异常");
    }

    @ExceptionHandler(BusinessException.class)
    public Result<String> businessExceptionHandler(BusinessException ex) {
        log.error(ex.getMessage(), ex);
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result<String> bindExceptionHandler(BindException e) {
        List<String> list = e.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());

        return Result.error(list.toString());
    }
}